import {
  CommentWithAuthor,
  fetchCommentsByPostId,
} from "@/prisma/queries/comments";
import Image from "next/image";
import React from "react";
import CommentCreateForm from "./comment-create-form";

export default async function CommentShow({
  comment,
}: {
  comment: CommentWithAuthor;
}) {
  const comments = await fetchCommentsByPostId(comment.postId || "");

  const children = comments.filter((c) => c.parentId === comment.id);

  return (
    <div className="p-4 border mt-2 rounded">
      <div className="flex gap-3">
        <Image
          src={comment.User?.image || "/avatar.jpg"}
          alt="user image"
          width={40}
          height={40}
          className="w-10 h-10 rounded-full"
        />
        <div className="flex-1 space-y-3">
          <p className="text-sm font-medium text-gray-500">
            {comment.User?.name}
          </p>
          <p className="flex justify-between">
            <span className="text-gray-900">{comment.content}</span>
            <span className="text-sm text-gray-400">
              {comment.createdAt.toLocaleString()}
            </span>
          </p>
          <CommentCreateForm
            postId={comment.postId || ""}
            parentId={comment.id || ""}
          />
        </div>
      </div>
      <div className="pl-12">
        {children
          .map((comment) => {
            return <CommentShow key={comment.id} comment={comment} />;
          })}
      </div>
    </div>
  );
}
